package com.sdp.wz.excel;

import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.sdp.right.excel.importExcel.ImportExcelCallbackService;
import com.sdp.wz.db.wz_info.entity.WzInfo;
import com.sdp.wz.db.wz_info.service.IWzInfoService;
import com.sdp.wz.db.wz_input.entity.WzInput;
import com.sdp.wz.db.wz_input.service.IWzInputService;
import com.sdp.wz.db.wz_input_detail.entity.WzInputDetail;
import com.sdp.wz.db.wz_input_detail.service.IWzInputDetailService;

@Service
public class WzInputDetailImportAfter implements ImportExcelCallbackService{
	
	@Autowired
	private IWzInputDetailService iWzInputDetailService;
	
	@Autowired
	private IWzInputService iWzInputService;
	
	@Autowired
	private IWzInfoService iWzInfoService;

	@Override
	@Transactional(rollbackFor=Exception.class)
	public void execute(HttpServletRequest request, HttpServletResponse response) {
		String imoprtParameter = request.getParameter("imoprtParameter");
		String inputCode = JSON.parseObject(imoprtParameter).getString("inputCode");
		LambdaQueryWrapper<WzInput> queryWrapper = new LambdaQueryWrapper<>();
		queryWrapper.eq(WzInput::getInputCode, inputCode);
		WzInput input = iWzInputService.getOne(queryWrapper,false);
		
		LambdaQueryWrapper<WzInputDetail> detailQuery = new LambdaQueryWrapper<>();
		detailQuery.eq(WzInputDetail::getInputCode, inputCode);
		List<WzInputDetail> detailList = iWzInputDetailService.list(detailQuery);
	
		List<String> wzNos = new ArrayList<String>();
		if(detailList!=null && detailList.size()>0) {
			for(WzInputDetail detail : detailList) {
				wzNos.add(detail.getWzNo());
				
				detail.setOrgNo(input.getOrgNo());
				detail.setVendorCode(input.getVendorCode());
				detail.setNowNum(detail.getInputNum());
				detail.setCreateTime(LocalDateTime.now());
			}
			
			Map<String,WzInfo> wzInfoMap = iWzInfoService.queryWzInfoMapByWzNos(wzNos);
			for(WzInputDetail detail : detailList) {
				if(wzInfoMap.containsKey(detail.getWzNo())) {
					detail.setWzUnit(wzInfoMap.get(detail.getWzNo()).getWzUnit());
					detail.setWzModel(wzInfoMap.get(detail.getWzNo()).getWzModel());
				}
				
			}
			
			iWzInputDetailService.updateBatchById(detailList);
			
		}
	}

}
